package org.jeecg.modules.mes.storage.controller;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.mes.client.TransactionClient;
import org.jeecg.modules.mes.order.entity.MesOrderProduce;
import org.jeecg.modules.mes.storage.entity.MesLackMaterial;
import org.jeecg.modules.mes.storage.entity.MesStockManage;
import org.jeecg.modules.mes.storage.service.IMesLackMaterialService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.mes.storage.service.IMesStockManageService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 仓库管理-缺料管理
 * @Author: jeecg-boot
 * @Date:   2020-11-11
 * @Version: V1.0
 */
@Api(tags="仓库管理-缺料管理")
@RestController
@RequestMapping("/storage/mesLackMaterial")
@Slf4j
public class MesLackMaterialController extends JeecgController<MesLackMaterial, IMesLackMaterialService> {
	 @Autowired
	 private IMesLackMaterialService mesLackMaterialService;
	 @Autowired
	 private IMesStockManageService mesStockManageService;
	 @Autowired
	 TransactionClient transactionClient;

	/**
	 * 分页列表查询
	 *
	 * @param mesLackMaterial
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "仓库管理-缺料管理-分页列表查询")
	@ApiOperation(value="仓库管理-缺料管理-分页列表查询", notes="仓库管理-缺料管理-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(MesLackMaterial mesLackMaterial,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<MesLackMaterial> queryWrapper = QueryGenerator.initQueryWrapper(mesLackMaterial, req.getParameterMap());
		Page<MesLackMaterial> page = new Page<MesLackMaterial>(pageNo, pageSize);
		IPage<MesLackMaterial> pageList = mesLackMaterialService.page(page, queryWrapper);
		List<MesLackMaterial> mesLackMaterialList = pageList.getRecords();
		if(mesLackMaterialList.size() != 0){
			for (MesLackMaterial lackMaterial : mesLackMaterialList) {
				if(StringUtils.isNotBlank(lackMaterial.getOrderId())){
					String orderId = lackMaterial.getOrderId();
					MesOrderProduce produce = transactionClient.queryMesProduceById(orderId);
					if(produce == null){
						mesLackMaterialService.removeById(lackMaterial.getId());
					}
				}
				String mCode = lackMaterial.getMaterielCode();
				//通过物料料号获取该物料的库存数据
				QueryWrapper<MesStockManage> wrapper = new QueryWrapper<>();
				wrapper.eq("materiel_code",mCode);
				MesStockManage stockManage = mesStockManageService.getOne(wrapper);
				if(stockManage != null){
					BigDecimal stockNum = new BigDecimal(stockManage.getStockNum());//库存数量
					BigDecimal lackNum = new BigDecimal(lackMaterial.getLackNum());//缺料数量
					//如果库存数量大于缺料数量,则删除该物料的缺料清单
					if(stockNum.compareTo(lackNum) > -1){
						mesLackMaterialService.removeById(lackMaterial);
					}else {
						lackMaterial.setStockNum(stockNum.toString());
						mesLackMaterialService.updateById(lackMaterial);
					}
				}
			}
		}
		IPage<MesLackMaterial> newPageList = mesLackMaterialService.page(page, queryWrapper);
		return Result.ok(newPageList);
	}


	 @PostMapping(value = "/addLack")
	 public String addLack(@RequestBody MesLackMaterial mesLackMaterial) {
		QueryWrapper<MesLackMaterial> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("materiel_code",mesLackMaterial.getMaterielCode());
		 MesLackMaterial lackMaterial = mesLackMaterialService.getOne(queryWrapper);
		 if(lackMaterial == null){
			 mesLackMaterialService.save(mesLackMaterial);
		 }
		 return "添加成功！";
	 }

	/**
	 *   添加
	 *
	 * @param mesLackMaterial
	 * @return
	 */
	@AutoLog(value = "仓库管理-缺料管理-添加")
	@ApiOperation(value="仓库管理-缺料管理-添加", notes="仓库管理-缺料管理-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody MesLackMaterial mesLackMaterial) {
		mesLackMaterialService.save(mesLackMaterial);
		return Result.ok("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param mesLackMaterial
	 * @return
	 */
	@AutoLog(value = "仓库管理-缺料管理-编辑")
	@ApiOperation(value="仓库管理-缺料管理-编辑", notes="仓库管理-缺料管理-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody MesLackMaterial mesLackMaterial) {
		mesLackMaterialService.updateById(mesLackMaterial);
		return Result.ok("编辑成功!");
	}

	 @PutMapping(value = "/myEdit")
	 public String myEdit(@RequestBody MesLackMaterial mesLackMaterial) {
		 mesLackMaterialService.updateById(mesLackMaterial);
		 return "编辑成功!";
	 }

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "仓库管理-缺料管理-通过id删除")
	@ApiOperation(value="仓库管理-缺料管理-通过id删除", notes="仓库管理-缺料管理-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		mesLackMaterialService.removeById(id);
		return Result.ok("删除成功!");
	}


	 @DeleteMapping(value = "/deleteByorderId")
	 public String deleteByorderId(@RequestParam(name="orderId",required=true) String orderId,
								   @RequestParam(name="mCode",required=false) String mCode) {
		 QueryWrapper<MesLackMaterial> queryWrapper = new QueryWrapper<>();
		 if(StringUtils.isNotBlank(mCode)){
			 queryWrapper.eq("order_id", orderId).eq("materiel_code",mCode);
		 }else {
			 queryWrapper.eq("order_id", orderId);
		 }
		 mesLackMaterialService.remove(queryWrapper);
		 return "删除成功!";
	 }


	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "仓库管理-缺料管理-批量删除")
	@ApiOperation(value="仓库管理-缺料管理-批量删除", notes="仓库管理-缺料管理-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.mesLackMaterialService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "仓库管理-缺料管理-通过id查询")
	@ApiOperation(value="仓库管理-缺料管理-通过id查询", notes="仓库管理-缺料管理-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		MesLackMaterial mesLackMaterial = mesLackMaterialService.getById(id);
		if(mesLackMaterial==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(mesLackMaterial);
	}

	 @GetMapping(value = "/getByOrderItemId")
	 public MesLackMaterial getByOrderItemId(@RequestParam(name="orderItemId",required=true) String orderItemId) {
		 QueryWrapper<MesLackMaterial> queryWrapper = new QueryWrapper<>();
		 queryWrapper.eq("produce_itemid", orderItemId);
		 MesLackMaterial mesLackMaterial = mesLackMaterialService.getOne(queryWrapper);
		 return mesLackMaterial;
	 }

	 @GetMapping(value = "/queryByOrderId")
	 public List<MesLackMaterial> queryByOrderId(@RequestParam(name="orderId",required=true) String orderId) {
		 QueryWrapper<MesLackMaterial> queryWrapper = new QueryWrapper<>();
		 queryWrapper.eq("order_id", orderId);
		 List<MesLackMaterial> lackMaterialList = mesLackMaterialService.list(queryWrapper);
		 return lackMaterialList;
	 }

    /**
    * 导出excel
    *
    * @param request
    * @param mesLackMaterial
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, MesLackMaterial mesLackMaterial) {
        return super.exportXls(request, mesLackMaterial, MesLackMaterial.class, "仓库管理-缺料管理");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, MesLackMaterial.class);
    }

}
